package cn.com.nes.site.service.crm.order.impl;

import cn.com.nes.common.exception.IllegalBusinessException;
import cn.com.nes.common.exception.MissBusinessParameterException;
import cn.com.nes.common.util.CopyUtils;
import cn.com.nes.mybatis.agent.crm.entity.Customer;
import cn.com.nes.mybatis.agent.crm.mapper.CustomerMapper;
import cn.com.nes.mybatis.agent.ope.entity.SalePriceDetail;
import cn.com.nes.mybatis.agent.ope.entity.SalePriceMaster;
import cn.com.nes.mybatis.agent.ope.mapper.SalePriceDetailMapper;
import cn.com.nes.mybatis.agent.ope.mapper.SalePriceMasterMapper;
import cn.com.nes.mybatis.agent.system.entity.TUser;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.entity.bo.crm.sale.CopySalePriceDetailBO;
import cn.com.nes.site.entity.bo.crm.sale.CopySalePriceMasterBO;
import cn.com.nes.site.entity.dto.product.GGoodsDTO;
import cn.com.nes.site.entity.em.DeleteEnum;
import cn.com.nes.site.entity.em.crm.saleorder.SaleOrderDistributeStatusEnum;
import cn.com.nes.site.entity.em.crm.saleorder.SignSaleOrderStatusEnum;
import cn.com.nes.site.entity.vo.crm.SalePriceDetailVO;
import cn.com.nes.site.entity.vo.crm.SalePriceMasterVO;
import cn.com.nes.site.entity.vo.crm.sale.MarkSaleOrderDispatchedVO;
import cn.com.nes.site.entity.vo.workOrder.UpdatePriceDetailVO;
import cn.com.nes.site.service.crm.order.SaleOrderInfoService;
import cn.com.nes.site.service.crm.order.SalePriceDetailService;
import cn.com.nes.site.service.crm.order.SalePriceService;
import cn.com.nes.site.service.crm.order.bo.CancelPriceMasterBO;
import cn.com.nes.site.service.crm.order.bo.QuerySalePriceMasterBO;
import cn.com.nes.site.service.crm.order.bo.SaleDetailBO;
import cn.com.nes.site.service.crm.order.bo.SaleMasterBO;
import cn.com.nes.site.service.crm.order.dto.SalePriceDetailDTO;
import cn.com.nes.site.service.crm.order.dto.SalePriceMasterDTO;
import cn.com.nes.site.service.product.GGoodsService;
import cn.com.nes.site.service.system.dict.TParamService;
import cn.com.nes.site.service.system.user.SystemUserService;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 销售订单 - 系统单实现
 */
@Slf4j
@Service
public class SalePriceServiceImpl extends ServiceImpl<SalePriceMasterMapper, SalePriceMaster> implements SalePriceService {

    private static final boolean IS_DEL_NO = false; // 是否删除 - 没删除

    private static final boolean IS_DEL_YES = true; // 是否删除 - 删除

    private static final Integer PRODUCT_TYPE_EQUIPMENT = 0;  // 产品类型 - 设备

    private static final Integer PRICE_SHEET_STATUS_CONFIRMING = 0;  // 报价单状态 - 待确认

    private static final Integer PRICE_SHEET_STATUS_ADOPT = 1;  // 报价单状态 - 通过

    @Resource
    private SystemUserService systemUserService;

    @Resource
    private TParamService tParamService;

    @Resource
    private SalePriceDetailMapper salePriceDetailMapper;

    @Resource
    private GGoodsService gGoodsService;

    @Resource
    private SaleOrderInfoService saleOrderInfoService;

    @Resource
    private CustomerMapper customerMapper;

    @Resource
    private SalePriceDetailService salePriceDetailService;

    @Override
    public PageData getPriceSheetList(SalePriceMasterVO vo) {
        // 组装分页参数
        Page<SalePriceMasterDTO> page = new Page<>(vo.getPageid(), vo.getPagesize());
        List<SalePriceMasterDTO> list = this.baseMapper.getPriceSheetList(page, vo);
        return PageData.ok(page, list);
    }

    /**
     * 查询系统单详情 - 封装返回
     */
    @Override
    public PageData getPriceSheetDetail(SalePriceMasterVO vo) {
        Page<SalePriceMasterDTO> page = new Page<>(1, 1);
        SalePriceMasterDTO priceSheetDetail = getPriceSheetDetail(vo.getId());
        List<SalePriceMasterDTO> list = Collections.singletonList(priceSheetDetail);
        return PageData.ok(page, list);
    }

    /**
     * 查询系统单详情 - 实体返回
     */
    @Override
    public SalePriceMasterDTO getPriceSheetDetail(Long id) {
        SalePriceMasterDTO priceSheetDetail = this.baseMapper.getPriceSheetDetail(id);
        log.debug("系统报价单主体:" + priceSheetDetail);

        List<SalePriceDetailDTO> detailList = salePriceDetailMapper.getDetailList(id);
        if (CollectionUtil.isNotEmpty(detailList)) {
            for (SalePriceDetailDTO detail : detailList) {
                // 查询创建人姓名
                TUser userInfo = systemUserService.getUserInfoByUserId(detail.getGmtCreateId());
                String gmtCreateName = StrUtil.EMPTY;
                if (ObjectUtil.isNotNull(userInfo)) {
                    gmtCreateName = userInfo.getNickName();
                }
                detail.setGmtCreateName(gmtCreateName);
                // 查询报价类型名称
                String typeName = tParamService.getNameByParamTypeAndValue("307", String.valueOf(detail.getType()));
                detail.setTypeName(typeName);
            }
            // 报价单设备列表
            log.debug("系统报价单设备列表:" + detailList);
            priceSheetDetail.setChildList(detailList);
        }

        // 设置创建人姓名
        TUser userInfo = systemUserService.getUserInfoByUserId(priceSheetDetail.getGmtCreateId());
        String gmtCreateName = StrUtil.EMPTY;
        if (ObjectUtil.isNotNull(userInfo)) {
            gmtCreateName = userInfo.getNickName();
        }
        priceSheetDetail.setGmtCreateName(gmtCreateName);
        // 设置客户姓名和电话号
        Customer customer = customerMapper.selectById(priceSheetDetail.getCustomerId());
        if (ObjectUtil.isNotNull(customer)) {
            priceSheetDetail.setCustomerName(customer.getCustomerName());
            priceSheetDetail.setCustomerPhone(customer.getPhone());
        }
        return priceSheetDetail;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageData addPriceSheet(SalePriceMasterVO vo) throws Exception {
        boolean flag = false;
        // 保存主表信息
        SalePriceMaster priceSheet = new SalePriceMaster();
        BeanUtils.copyProperties(vo, priceSheet);
        Long id = priceSheet.getId();
        // 新增
        if (Objects.isNull(id)) {
            priceSheet.setDeleted(IS_DEL_NO);
            priceSheet.setGmtCreate(vo.getOperateDate());
            priceSheet.setGmtCreateId(vo.getOperateUserId());
            priceSheet.setGmtModified(vo.getOperateDate());
            priceSheet.setGmtModifiedId(vo.getOperateUserId());
            priceSheet.setCompanyId(vo.getUserInfo().getCompanyId());
            if (ObjectUtil.isNull(priceSheet.getStatus())) {
                priceSheet.setStatus(PRICE_SHEET_STATUS_CONFIRMING); // 默认待客户验证
            }
            /* priceSheet.setCustomerId(saleOrderInfoService.getSaleOrderById(vo.getOrderId()).getCustomerId());*/
            this.baseMapper.insert(priceSheet);

            id = priceSheet.getId();
        } else { // 修改
            boolean checkFlag = checkPriceSheet(priceSheet);
            if (!checkFlag) {
                //报价单已被使用，修改失败!
                return PageData.ok("id", id);
            }

            flag = true;
            priceSheet.setGmtModified(vo.getOperateDate());
            priceSheet.setGmtModifiedId(vo.getOperateUserId());

            this.baseMapper.updateById(priceSheet);
        }

        // 保存子表信息
        List<SalePriceDetailVO> childList = vo.getChildList();
        if (CollectionUtil.isNotEmpty(childList)) {
            // 如果是修改，则需要判断是否删除子表元素
            if (flag) {
                // 筛选子表的单个元素：在数据库表里，但是不在入参里面，这部分要删除
                List<Long> detailIdList = salePriceDetailMapper.getDetailIdList(id);
                List<Long> list = new ArrayList<>();
                for (Long detailId : detailIdList) {
                    int count = 0;
                    for (SalePriceDetailVO child : childList) {
                        if (Objects.isNull(child.getId())) {
                            continue;
                        }
                        if (detailId.equals(child.getId())) {
                            count++;
                        }
                    }
                    if (count == 0) {
                        list.add(detailId);
                    }
                }
                // 删除筛选出的子表元素 - 逻辑删除
                log.info("删除的子表元素:" + list);
                if (CollectionUtil.isNotEmpty(list)) {
                    for (Long detailId : list) {
                        SalePriceDetail salePriceDetail = new SalePriceDetail();
                        salePriceDetail.setId(detailId);
                        salePriceDetail.setDeleted(IS_DEL_YES);
                        salePriceDetail.setGmtModified(vo.getOperateDate());
                        salePriceDetail.setGmtModifiedId(vo.getOperateUserId());
                        salePriceDetailMapper.updateById(salePriceDetail);
                    }
                }
            }

            // 保存子表
            for (SalePriceDetailVO detailVO : childList) {
                SalePriceDetail salePriceDetail = new SalePriceDetail();
                BeanUtils.copyProperties(detailVO, salePriceDetail);

                salePriceDetail.setOrderId(priceSheet.getOrderId()); // 设置订单id
                salePriceDetail.setPriceMasterId(id); // 设置父id

                if (Objects.isNull(salePriceDetail.getId())) {
                    salePriceDetail.setDeleted(IS_DEL_NO);
                    salePriceDetail.setGmtCreate(vo.getOperateDate());
                    salePriceDetail.setGmtCreateId(vo.getOperateUserId());
                    salePriceDetail.setGmtModified(vo.getOperateDate());
                    salePriceDetail.setGmtModifiedId(vo.getOperateUserId());

                    salePriceDetailMapper.insert(salePriceDetail);
                } else {
                    salePriceDetail.setGmtModified(vo.getOperateDate());
                    salePriceDetail.setGmtModifiedId(vo.getOperateUserId());

                    salePriceDetailMapper.updateById(salePriceDetail);
                }
            }
        }
        return PageData.ok("id", id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Deprecated
    public PageData copyPriceSheet(SalePriceMasterVO vo) {
        SalePriceMaster oldPriceSheet = this.baseMapper.selectById(vo.getId());
        if (Objects.isNull(oldPriceSheet)) {
            return PageData.error("未查询到相关信息,复制失败");
        }
        // 复制主表信息
        SalePriceMaster newPriceSheet = new SalePriceMaster();
        BeanUtils.copyProperties(oldPriceSheet, newPriceSheet);

        newPriceSheet.setStatus(PRICE_SHEET_STATUS_CONFIRMING);
        newPriceSheet.setGmtCreate(vo.getOperateDate());
        newPriceSheet.setGmtCreateId(vo.getOperateUserId());
        newPriceSheet.setGmtModified(vo.getOperateDate());
        newPriceSheet.setGmtModifiedId(vo.getOperateUserId());

        this.baseMapper.insert(newPriceSheet);

        // 复制子表信息
        Long id = newPriceSheet.getId();
        List<SalePriceDetailDTO> oldDetailList = salePriceDetailMapper.getDetailList(vo.getId());

        if (CollectionUtil.isNotEmpty(oldDetailList)) {
            for (SalePriceDetailDTO oldDetail : oldDetailList) {
                SalePriceDetail newDetail = new SalePriceDetail();
                BeanUtils.copyProperties(oldDetail, newDetail);

                newDetail.setOrderId(newPriceSheet.getOrderId());
                newDetail.setPriceMasterId(id);
                newDetail.setGmtCreate(vo.getOperateDate());
                newDetail.setGmtCreateId(vo.getOperateUserId());
                newDetail.setGmtModified(vo.getOperateDate());
                newDetail.setGmtModifiedId(vo.getOperateUserId());

                salePriceDetailMapper.insert(newDetail);
            }
        }
        return PageData.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageData delPriceSheet(SalePriceMasterVO vo) {

        SalePriceMaster salePriceMaster = this.getById(vo.getId());
        if (SignSaleOrderStatusEnum._DISTRIBUTION.getKey() == salePriceMaster.getDistributeStatus()) {
            return PageData.error("当前报价单已派发工单,不可删除");
        }

        // 删除主表
        SalePriceMaster priceSheet = new SalePriceMaster();
        priceSheet.setId(vo.getId());
        priceSheet.setDeleted(IS_DEL_YES);
        priceSheet.setGmtModifiedId(vo.getOperateUserId());
        priceSheet.setGmtModified(vo.getOperateDate());

        boolean flag = checkPriceSheet(priceSheet);
        if (!flag) {
            return PageData.error("报价单已被使用，删除失败!");
        }

        this.baseMapper.updateById(priceSheet);

        // 删除子表
        vo.setGmtModified(vo.getOperateDate());
        vo.setGmtModifiedId(vo.getOperateUserId());
        salePriceDetailMapper.delDetail(vo);

        return PageData.ok();
    }

    @Override
    public void signPriceSheet(List<Long> priceSheetIdList, Long orderId, Long userId,
            boolean commit) throws Exception {
        if (!commit) {
            return;
        }
        String customerId = saleOrderInfoService.getSaleOrderById(orderId).getCustomerId();

        for (Long priceSheetId : priceSheetIdList) {
            SalePriceMaster priceSheet = new SalePriceMaster();
            priceSheet.setId(priceSheetId);
            priceSheet.setStatus(PRICE_SHEET_STATUS_ADOPT);    // 字典:1-通过
            priceSheet.setCustomerId(customerId);
            priceSheet.setGmtModified(new Date());
            priceSheet.setGmtModifiedId(userId);

            this.baseMapper.updateById(priceSheet);
        }
    }

    @Override
    public Boolean signPriceSheet(MarkSaleOrderDispatchedVO vo) {
        SalePriceMaster salePriceMaster = new SalePriceMaster();
        salePriceMaster.setId(vo.getPriceMasterId());
        salePriceMaster.setDistributeStatus(vo.getSignStatus());
        salePriceMaster.setGmtModified(vo.getOperateDate());
        salePriceMaster.setGmtModifiedId(vo.getOperateUserId());

        return this.updateById(salePriceMaster);
    }

    /**
     * 批量给系统单加标记
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelPriceMaster(CancelPriceMasterBO cancelPriceMasterBO) {
        if (CollectionUtil.isEmpty(cancelPriceMasterBO.getPriceMasterIdList())) {
            throw new IllegalBusinessException("priceMasterIdList must not empty");
        }

        QueryWrapper<SalePriceMaster> wrapper = new QueryWrapper<>();
        wrapper.in("id", cancelPriceMasterBO.getPriceMasterIdList());

        SalePriceMaster salePriceMaster = new SalePriceMaster();
        salePriceMaster.setDistributeStatus(SignSaleOrderStatusEnum._CANCEL.getKey());
        salePriceMaster.setGmtModified(cancelPriceMasterBO.getOperateDate());
        salePriceMaster.setGmtModifiedId(cancelPriceMasterBO.getOperateUserId());

        Integer rows = this.baseMapper.update(salePriceMaster, wrapper);
        if (rows <= 0) {
            throw new IllegalBusinessException("修改系统单派单状态失败");
        }
    }

    @Override
    public List<Long> getPriceSheetIdListByOrderId(Long orderId) {
        return this.baseMapper.getPriceSheetIdListByOrderId(orderId);
    }

    @Override
    public PageData getHistoryName(SalePriceMasterVO vo) {
        String userId = vo.getUserInfo().getId();
        List<String> historyNameList = this.baseMapper.getHistoryName(userId);

        Map<String, Object> map = new HashMap<>();
        map.put("historyNameList", historyNameList);
        return PageData.ok(map);
    }

    /**
     * 复制订单价格主表
     * @param copySalePriceMasterBo
     */
    @Override
    public void copySalePriceMaster(CopySalePriceMasterBO copySalePriceMasterBo) throws Exception {
        List<SalePriceMaster> sourceSalePriceMasters = this.baseMapper.getSalePriceMasters(copySalePriceMasterBo.getSourceSaleOrderId());
        for (SalePriceMaster sourceSalePriceMaster : sourceSalePriceMasters) {
            SalePriceMaster targetSalePriceMaster = new SalePriceMaster();
            BeanUtils.copyProperties(sourceSalePriceMaster, targetSalePriceMaster, "id");
            initSalePriceMaster(targetSalePriceMaster, copySalePriceMasterBo.getOperateUserId(), copySalePriceMasterBo.getOperateDate(), copySalePriceMasterBo.getOperateUserCompanyId());
            targetSalePriceMaster.setOrderId(copySalePriceMasterBo.getTargetSaleOrderId());
            this.save(targetSalePriceMaster);
            log.info("copySalePriceMaster - SalePriceMaster: {}", targetSalePriceMaster);

            CopySalePriceDetailBO copySalePriceDetailBO = new CopySalePriceDetailBO();
            BeanUtils.copyProperties(copySalePriceMasterBo, copySalePriceDetailBO);
            copySalePriceDetailBO.setSourcePriceMasterId(sourceSalePriceMaster.getId());
            copySalePriceDetailBO.setTargetPriceMasterId(targetSalePriceMaster.getId());
            salePriceDetailService.copySalePriceDetail(copySalePriceDetailBO);
        }

    }

    @Override
    public List<SalePriceMasterDTO> getPriceMastersAndDetails(Long saleOrderId) throws Exception {
        List<SalePriceMasterDTO> priceMasterDTOS = this.baseMapper.getPriceMasters(saleOrderId);
        for (SalePriceMasterDTO salePriceMasterDTO : priceMasterDTOS) {
            List<SalePriceDetailDTO> priceDetailDTOS = salePriceDetailService.getPriceDetails(salePriceMasterDTO.getId());
            salePriceMasterDTO.setChildList(priceDetailDTOS);
        }
        return priceMasterDTOS;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePriceDetail(UpdatePriceDetailVO vo) throws Exception {
        SalePriceMasterDTO priceSheetMaster = getPriceSheetDetail(vo.getPriceMasterId());
        if (ObjectUtil.isNull(priceSheetMaster)) {
            throw new Exception("未查询到系统单详情,修改失败");
        }
        // 删除旧的产品
        List<SalePriceDetailDTO> childList = priceSheetMaster.getChildList();
        if (CollectionUtil.isNotEmpty(childList)) {
            for (SalePriceDetailDTO item : childList) {
                SalePriceDetail salePriceDetail = new SalePriceDetail();
                salePriceDetail.setId(item.getId());
                salePriceDetail.setDeleted(IS_DEL_YES);
                salePriceDetail.setGmtModified(vo.getOperateDate());
                salePriceDetail.setGmtModifiedId(vo.getOperateUserId());
                Integer rows = salePriceDetailMapper.updateById(salePriceDetail);
                if (!rows.equals(1)) {
                    throw new Exception("修改系统单产品失败!");
                }
            }
        }

        // 保存新的产品
        Integer i = 1;
        for (SalePriceDetailVO item : vo.getChildList()) {
            // 查询产品详情
            GGoodsDTO goodsDetail = gGoodsService.getGoodsDetailBySblx(item.getEquipmentId());
            // 保存系统单设备
            SalePriceDetail salePriceDetail = new SalePriceDetail();
            salePriceDetail.setOrderId(priceSheetMaster.getOrderId());
            salePriceDetail.setPriceMasterId(priceSheetMaster.getId());
            salePriceDetail.setEquipmentId(goodsDetail.getSblx());
            salePriceDetail.setEquipmentName(goodsDetail.getGoodsName());
            salePriceDetail.setEquipmentModel(goodsDetail.getGoodsModel());
            salePriceDetail.setBrandId(String.valueOf(goodsDetail.getBrandId()));
            salePriceDetail.setCompanyId(priceSheetMaster.getCompanyId());
            salePriceDetail.setCount(item.getCount());
            salePriceDetail.setUnit(Integer.valueOf(goodsDetail.getUnit()));
            salePriceDetail.setType(1); // 默认商品
            salePriceDetail.setDiscount(100); // 无折扣
            salePriceDetail.setPrice(goodsDetail.getPrice());
            salePriceDetail.setTotalPrice(ObjectUtil.isNull(salePriceDetail.getCount()) ? new BigDecimal(0) : salePriceDetail.getPrice()
                    .multiply(BigDecimal.valueOf(salePriceDetail.getCount())));
            salePriceDetail.setStatus(null); // 状态不管
            salePriceDetail.setSort(i++);
            salePriceDetail.setDeleted(IS_DEL_NO);
            salePriceDetail.setGmtCreateId(vo.getOperateUserId());
            salePriceDetail.setGmtCreate(vo.getOperateDate());
            salePriceDetail.setGmtModifiedId(vo.getOperateUserId());
            salePriceDetail.setGmtModified(vo.getOperateDate());

            Integer rows = salePriceDetailMapper.insert(salePriceDetail);
            if (!rows.equals(1)) {
                throw new Exception("修改系统单产品失败!");
            }
        }
    }

    @Override
    public void changeStatus(Long priceMasterId, Boolean flag) {
        SalePriceMaster salePriceMaster = new SalePriceMaster();
        salePriceMaster.setId(priceMasterId);
        salePriceMaster.setDistributeStatus(flag ? 1 : 0);

        this.baseMapper.updateById(salePriceMaster);
    }

    @Override
    public List<Long> getNotCancelSaleOrderIdList(List<Long> saleOrderIdList) {
        if (CollectionUtil.isEmpty(saleOrderIdList)) {
            throw new MissBusinessParameterException("saleOrderIdList must not empty");
        }

        QueryWrapper<SalePriceMaster> wrapper = new QueryWrapper<>();
        wrapper.select("order_id");
        wrapper.in("order_id", saleOrderIdList);
        wrapper.eq("distribute_status", SignSaleOrderStatusEnum._DISTRIBUTION.getKey());
        wrapper.eq("deleted", false);
        List<SalePriceMaster> salePriceMasters = this.baseMapper.selectList(wrapper);


        return salePriceMasters.stream().map(SalePriceMaster::getOrderId).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SalePriceMasterDTO saveMasterOrder(SaleMasterBO saleMasterBO) throws Exception {
        SalePriceMaster salePriceMaster = getSaleMaster(saleMasterBO.getMasterId());
        if (saleMasterBO.isAddMaster()) {
            salePriceMaster.setGmtCreateId(saleMasterBO.getOperateUserId());
            salePriceMaster.setGmtCreate(saleMasterBO.getOperateDate());
            salePriceMaster.setDeleted(Boolean.parseBoolean(String.valueOf(DeleteEnum._0.getKey())));
        }
        BeanUtils.copyProperties(saleMasterBO, salePriceMaster);
        salePriceMaster.setName(saleMasterBO.getSaleMasterName());
        salePriceMaster.setStatus(saleMasterBO.getSaleMasterStatus().getKey());
        salePriceMaster.setCustomerId(saleMasterBO.getCustomerUuid());
        salePriceMaster.setGmtModifiedId(saleMasterBO.getOperateUserId());
        salePriceMaster.setGmtModified(saleMasterBO.getOperateDate());
        this.saveOrUpdate(salePriceMaster);

        if (saleMasterBO.isHandleForExcelImport()) {
            SaleDetailBO saleDetailBO = saleMasterBO.getSaleDetails().get(0);
            List<SalePriceDetailDTO> priceDetails = salePriceDetailService.getPriceDetails(salePriceMaster.getId());
            if (CollectionUtil.isNotEmpty(priceDetails)) {
                SalePriceDetailDTO salePriceDetailDTO = priceDetails.get(0);
                saleDetailBO.setId(salePriceDetailDTO.getId());
                saleDetailBO.setAddDetail(Boolean.FALSE);
            } else {
                saleDetailBO.setAddDetail(Boolean.TRUE);
            }
            saleDetailBO.setPriceMasterId(salePriceMaster.getId());
            saleDetailBO.setOrderId(salePriceMaster.getOrderId());
            salePriceDetailService.saveOrderDetail(saleDetailBO);
        } else {

            for (SaleDetailBO saleDetailBO : saleMasterBO.getSaleDetails()) {
                saleDetailBO.setAddDetail(Boolean.TRUE);
                saleDetailBO.setPriceMasterId(salePriceMaster.getId());
                saleDetailBO.setOrderId(salePriceMaster.getOrderId());
                salePriceDetailService.saveOrderDetail(saleDetailBO);
            }
        }

        return getPriceSheetDetail(salePriceMaster.getId());
    }

    @Override
    public SalePriceMaster getPriceMaster(Long saleOrderId, String saleMasterName) throws Exception {
        return getOne(new QueryWrapper<SalePriceMaster>().eq("deleted", Boolean.FALSE)
                .eq("order_id", saleOrderId)
                .eq("name", saleMasterName));
    }

    @Override
    public List<SalePriceMasterDTO> getPriceMasterList(QuerySalePriceMasterBO queryBO) {
        QueryWrapper<SalePriceMaster> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", queryBO.getSaleOrderId());
        queryWrapper.eq("deleted", false);

        return CopyUtils.copyList(this.baseMapper.selectList(queryWrapper), SalePriceMasterDTO.class);
    }

    @Override
    public Integer queryHaveWorkOrder(Set<Long> saleOrderIdSet) {
        QueryWrapper<SalePriceMaster> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", false);
        queryWrapper.in("order_id", saleOrderIdSet);
        queryWrapper.eq("distribute_status", Integer.valueOf(SaleOrderDistributeStatusEnum.DISTRIBUTE.getKey()));

        return this.baseMapper.selectCount(queryWrapper);
    }

    private SalePriceMaster getSaleMaster(Long masterId) {
        if (ObjectUtil.isNull(masterId)) {
            return new SalePriceMaster();
        }
        SalePriceMaster salePriceMaster = this.getById(masterId);
        return ObjectUtil.isNull(salePriceMaster) ? new SalePriceMaster() : salePriceMaster;
    }

    private static void initSalePriceMaster(SalePriceMaster salePriceMaster, Long operateUserId, Date operateDate,
            String companyId) {
        salePriceMaster.setDeleted(Boolean.FALSE);
        salePriceMaster.setGmtCreate(operateDate);
        salePriceMaster.setGmtCreateId(operateUserId);
        salePriceMaster.setGmtModified(operateDate);
        salePriceMaster.setGmtModifiedId(operateUserId);
        salePriceMaster.setCompanyId(companyId);
    }

    // 校验报价单是否能修改
    private boolean checkPriceSheet(SalePriceMaster priceSheet) {
        boolean flag = true; // 能修改

        Integer status = this.baseMapper.getPriceSheetStatus(priceSheet.getId());
        if (PRICE_SHEET_STATUS_ADOPT.equals(status)) {
            flag = false; // 不能修改
        }
        return flag;
    }

}
